<template>
  <div class="home">
    <input placeholder="请输入用户token" v-model="userToken"/>
    <input type="button" value="连接WebSocket" @click="connectWebSocket"/>
    <div class="chatPanel">
      <div class="panel">
        <div v-for="(item, index) in list" :key="index">
          <div v-if="item.form == userToken" style="width: 100%;height: 50px;text-align:right;">
            <span class="text1">{{ item.content }}</span>
          </div>
          <div v-else style="width: 100%;height: 50px;text-align:left;">
            <span class="text1">{{ item.content }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="inputPanel">
      <!-- <input placeholder="收信人" v-model="to"/> -->
      <input placeholder="测试信息" v-model="message">
      <input type="button" value="测试信息发送" @click="sendMessage"/>
      <!-- <input type="button" value="加载聊天记录" @click="loadChatHistory"/> -->
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'home',
  data() {
    return {
      userToken: '',
      ws: null,
      to: '',
      list: [],
      message: '',
    }
  },
  computed: {
    canSend() {
      return this.userToken && this.message.trim();
    }
  },
  methods: {
    connectWebSocket() {
      const wsUrl = `ws://192.168.40.61:8080/zsd-merchant/websocket?token=${this.userToken}`;
      this.ws = new WebSocket(wsUrl);
      this.ws.onopen = () => {
        console.log('客户端与服务器连接成功');
      };
      this.ws.onmessage = (e) => {
        console.log('客户端收到服务器的消息:', e.data);
        let parsedMessage = JSON.parse(e.data); // 解析消息数据
        this.list.push(parsedMessage); // 使用解析后的消息对象
      };
      this.ws.onerror = (error) => {
        console.error('WebSocket错误:', error);
        this.$message.error('连接错误，请刷新页面重试');
      };
      this.ws.onclose = () => {
        console.log('连接关闭');
        this.ws = null; // 设置为null以便后续检测
      };
    },
    sendMessage() {
      if (!this.canSend) {
        return;
      }
      const message = {
        content: this.message,
        to: this.to,
        type: 'text',
        form: this.userToken,
        formType: 'admin'
      };
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(JSON.stringify(message));
        this.list.push(message);
        this.message = '';
        this.$message.success('发送成功');
      } else {
        this.$message.error('连接已断开，请刷新页面重试');
      }
    },
    loadChatHistory() {
      const date = new Date().toISOString().slice(0, 10).replace(/-/g, ''); // 获取当前日期，格式为yyyyMMdd
      axios.get(`/chat-history/query`, {
        params: {
          form: this.userToken,
          to: this.to,
          date: date
        }
      })
      .then(response => {
        this.list = response.data.data; // 假设后端返回的数据可以直接赋值给list
        console.log(this.list)
      })
      .catch(error => {
        console.error('Error fetching chat history:', error);
      });
    }
  },
  created() {
    this.connectWebSocket();
  },
  beforeDestroy() {
    if (this.ws) {
      this.ws.close();
    }
  }
}
</script>

<style scoped>
.chatPanel{
  width:800px;
  height: 400px;
  margin:0 auto;
  border:1px solid #ccc;
  overflow:auto;
}
.inputPanel{
  width:800px;
  height:100px;
  margin:0 auto;
  border:1px solid #ccc;
}
.inputPanel div{
  float:left;
}
.text1 {
  padding: 10px;
  margin: 5px;
  background-color: lightgray;
  border-radius: 5px;
}
</style>